//
//  VOLChangePersonDataViewController.m
//  Volver
//
//  Created by admin on 14-10-8.
//  Copyright (c) 2014年 vol. All rights reserved.
//

#import "VOLChangePersonDataViewController.h"

#import "common.h"
#import "HTTPDefine.h"

#import "VOLAppDelegate.h"
#import "HYLContact.h"
#import "HYLContactGroup.h"
#import "VOLChangePasswordViewController.h"

#import "ASIHTTPRequest.h"
#import "ASIFormDataRequest.h"
#import "JSONKit.h"
#import "MBProgressHUD.h"

@interface VOLChangePersonDataViewController ()
{
    
    VOLAppDelegate *del;
    int currentHeight;
    NSMutableArray *dataArray;
    NSMutableArray *arraySex;
    
    UITableView *tableViewDate;
    
    UITextField *textPwd;
    UITextField *textMail;
    
    UITextField *textName;
    NSString *stringName;
    NSString *stringEmail;
    NSString *stringSex;
    NSString *stringBirthDay;
    double birth;
    NSString *stringPwd;
    
    UIDatePicker *da;
    UIPickerView *sexPicker;
    
    BOOL dataFlag;
    BOOL sexFlag;
    JSONDecoder *json;
    
    MBProgressHUD *HUD;
    UITapGestureRecognizer *tap;
    
    NSDateFormatter *formatter;
}

@end

@implementation VOLChangePersonDataViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = @"编辑个人信息";
    tableViewDate.backgroundColor = [UIColor whiteColor];
	addBackButton();
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"保存" style:UIBarButtonItemStylePlain target:self action:@selector(savePersonData:)];
    [self.navigationItem.rightBarButtonItem setTintColor:kThemeColor];
    //分组样式
    tableViewDate = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStyleGrouped];
    tableViewDate.dataSource = self;
    tableViewDate.delegate = self;
    //    [tableViewDate footerViewForSection:1];
    //在talbeView加 footerView 回收picker
    
    tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(hiddenPicker)];
    
    //初始化一些对象
    del = kGetDel;
    formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"yyyy年MM月dd日"];
    
    //判断：如果为空则=@"",否则将值赋给对应项
    if ((NSNull *)del.currentUser.userName == [NSNull null]) {
        stringName = @"";
    }
    else
        stringName = del.currentUser.userName;
    if ((NSNull *)del.currentUser.userSex == [NSNull null]) {
        stringSex = @"男性";
    }else
        stringSex = del.currentUser.userSex;
    if ((NSNull *)del.currentUser.userMail == [NSNull null]) {
        stringEmail = @"";
    }else
        stringEmail = del.currentUser.userMail;
    
    if ((NSNull *)del.currentUser.userPassword == [NSNull null]) {
        stringPwd = @"";
    }else{
        stringPwd = del.currentUser.userPassword;
    }
    
    
    if (del.currentUser.userBirth == 0) {
        stringBirthDay = @"";
    }else {
        NSDate *date =  kTransformToDate(del.currentUser.userBirth);
        
        stringBirthDay = [formatter stringFromDate:date];
    }
    
    [self initData];
    [self.view addSubview:tableViewDate];
    
    da = [[UIDatePicker alloc]initWithFrame:CGRectMake(320, 480, 0, 0)];
    da.datePickerMode = UIDatePickerModeDate;
    da.locale = [NSLocale currentLocale];
    [da setBackgroundColor:[UIColor whiteColor]];
    [self.view addSubview:da];
    //UIPickerView 性别
    arraySex = [NSMutableArray arrayWithObjects:@"男性",@"女性",@"其他", nil];
    sexPicker = [[UIPickerView alloc]initWithFrame:CGRectMake(320, 480, 0, 0)];
    [sexPicker setBackgroundColor:[UIColor whiteColor]];
    [sexPicker setAccessibilityElementsHidden:YES];
    [sexPicker setUserInteractionEnabled:YES];
    sexPicker.dataSource = self;
    sexPicker.delegate = self;
    [self.view addSubview:sexPicker];
    //初始化flag
    dataFlag = NO;
    sexFlag = NO;
    //初始化json
    json = [[JSONDecoder alloc]init];
    
    birth = del.currentUser.userBirth;
    stringSex = del.currentUser.userSex;
    stringEmail = del.currentUser.userMail;
}


#pragma mark 加载数据
-(void)initData
{
    dataArray = [[NSMutableArray alloc]init];
    //修改私人信息
    HYLContact *contact5 = [[HYLContact alloc]initWithTitleValue:@"名字" changeValue:stringName];
    HYLContact *contact1 = [[HYLContact alloc]initWithTitleValue:@"性别" changeValue:stringSex];
    HYLContact *contact2 = [[HYLContact alloc]initWithTitleValue:@"出生日期" changeValue:stringBirthDay];
    HYLContact *contact3 = [[HYLContact alloc]initWithTitleValue:@"电子邮箱" changeValue:stringEmail];
    
    HYLContactGroup *group1 = [[HYLContactGroup alloc]initWithName:@"私人信息" andDetail:@"" andContacts:[NSMutableArray arrayWithObjects:contact5,contact1,contact2,contact3, nil]];
    [dataArray addObject:group1];
    
    //修改密码
    HYLContact *contact4 = [[HYLContact alloc]initWithTitleValue:@"密码" changeValue:stringPwd];
    HYLContactGroup *group2 = [[HYLContactGroup alloc]initWithName:@"修改密码" andDetail:@"" andContacts:[NSMutableArray arrayWithObjects:contact4, nil]];
    [dataArray addObject:group2];
    
}

#pragma mark 返回按钮事件
-(void)goBack:(id)sender{
    back;
}

#pragma mark 隐藏DatePicker和PickerView
-(void)hiddenPicker
{
    if (sexFlag) {
        [UIView animateWithDuration:0.3 animations:^{
            sexPicker.transform = CGAffineTransformIdentity;
        } completion:^(BOOL finished) {
            sexFlag = NO;
        }];
        //移除手势
        [self.view removeGestureRecognizer:tap];
        
        NSInteger row = [sexPicker selectedRowInComponent:0];
        stringSex = [arraySex objectAtIndex:row];
        if ((NSNull *)del.currentUser.userMail == [NSNull null]) {
            stringEmail = @"";
            del.currentUser.userMail = @"";
        }else
            
            stringEmail = del.currentUser.userMail;
        
        [self initData];
        [tableViewDate reloadData];
        
    }
    
    if (dataFlag) {
        [UIView animateWithDuration:0.3 animations:^{
            da.transform = CGAffineTransformIdentity;
        } completion:^(BOOL finished) {
            dataFlag = NO;
        }];
        //移除手势
        [self.view removeGestureRecognizer:tap];
        
        //将日期转化为string显示
        NSDate *date = da.date;
        birth = [date timeIntervalSince1970];
        NSDate *noetime = [NSDate date];
        double nowtime = [noetime timeIntervalSince1970];
        if (birth >= nowtime) {
            HUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
            [self.navigationController.view addSubview:HUD];
            
            HUD.mode = MBProgressHUDModeText;
            
            HUD.labelText = @"出生日期大于当前日期";
            [HUD showAnimated:YES whileExecutingBlock:^{
                sleep(1);
            } completionBlock:^{
                [HUD removeFromSuperview];
                HUD = nil;
                
                stringBirthDay = @"";
                [self initData];
                [tableViewDate reloadData];
                
            }];
            
            
        }
        else{
            
            stringBirthDay = [formatter stringFromDate:date];
            [self initData];
            [tableViewDate reloadData];
            
        }
    }
    
    
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

#pragma mark 验证密码
-(int)checkPassword:(NSString *)oldPwd{
    //使用POST方法发送
    NSString *urlstr = [NSString stringWithFormat:@"%@user/checkPassword",kHTTPHome];
    NSURL *url = [NSURL URLWithString:urlstr];
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
    //设置数据
    [request setPostValue:del.currentUser.userPhone forKey:@"userPhone"];
    [request setPostValue:[MD5 md5HexDigest:oldPwd] forKey:@"userPassword"];
    
    //设置请求方式
    [request setRequestMethod:@"POST"];
    
    
    //发送同步请求
    [request startSynchronous];
    
    if (request.error != nil) {
        NSLog(@"请求失败");
        return -2;
    }
    
    
    NSData *data = [request responseData];
    
    //若没有数据返回，直接结束函数
    if (data == nil) {
        NSLog(@"checkPassword---data为空");
        return -1;
    }
    
    NSDictionary *dic = [json objectWithData:data];
    int status = [[dic objectForKey:@"status"] intValue];
    return status;
    
}



#pragma mark - 代理方法
#pragma mark - UITableVIew代理方法
#pragma mark 返回分组数
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    
    return [dataArray count];
}

#pragma mark 返回每组行数
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    HYLContactGroup *group = dataArray[section];
    return group.contacts.count;
}

#pragma mark 返回每行的单元格
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    HYLContactGroup *group = dataArray[indexPath.section];
    HYLContact *contact = group.contacts[indexPath.row];
    
    UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:nil];
    
    cell.textLabel.text = [contact getTitleValue];
    NSString *detailTemp = [contact getChangeValue];
    if ([detailTemp isEqualToString:@"<null>"]) {
        if (indexPath.section == 0 && indexPath.row == 1) {
            cell.detailTextLabel.text = @"男性";
        }
        
    }else{
        cell.detailTextLabel.text = [contact getChangeValue];
    }
    
    //当显示密码时用＊显示
    if (indexPath.section == 1 && [indexPath row] == 0) {
        
        cell.detailTextLabel.text = @"******";
    }
    cell.detailTextLabel.textColor = [UIColor darkGrayColor];
    return cell;
    
}

#pragma mark 点击cell时触发的事件
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //取消被点击时的背景色
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    
    HYLContactGroup *group = dataArray[indexPath.section];
    HYLContact *contact = group.contacts[indexPath.row];
    if (indexPath.section == 0 && [indexPath row] == 0)
    {
        
        //修改名字
        if ((NSNull *)stringName == [NSNull null]) {
            stringName = @"";
        }else
            
            stringName = del.currentUser.userName;
        
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"名字" message:stringName delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        alert.tag = 1000+3;
        alert.alertViewStyle = UIAlertViewStylePlainTextInput;
        textName = [alert textFieldAtIndex:0];
        if ((NSNull *)del.currentUser.userName == [NSNull null]) {
            stringName = @"";
        }else
            
            textName.text = [contact getChangeValue];
        [alert show];
        
        
    }
    if (indexPath.section == 0 && [indexPath row] == 1)
    {
        //添加手势
        [self.view addGestureRecognizer:tap];
        
        //修改性别
        if (!sexFlag) {
            [UIView animateWithDuration:0.3 delay:0 options:UIViewAnimationOptionLayoutSubviews animations:^{
                if (dataFlag) {
                    da.transform = CGAffineTransformIdentity;
                    dataFlag = NO;
                }
                sexPicker.transform = CGAffineTransformTranslate(sexPicker.transform, -320, -(490-175));
            } completion:^(BOOL finished) {
                sexFlag = YES;
                NSLog(@"向上移动·");
            }];
        }
    }
    
    
    if (indexPath.section == 0 && [indexPath row] == 2)
    {
        //添加手势
        [self.view addGestureRecognizer:tap];
        
        if (!dataFlag) {
            //修改出生日期
            [UIView animateWithDuration:0.3 delay:0 options:UIViewAnimationOptionLayoutSubviews animations:^{
                HYLContactGroup *group = dataArray[indexPath.section];
                HYLContact *contact = group.contacts[indexPath.row];
                if (!([contact.changeValue isEqualToString:@""] || contact.changeValue == nil)) {
                    da.date = [formatter dateFromString:contact.changeValue];
                }
                
                da.transform = CGAffineTransformTranslate(da.transform, -320, -(480-210));
                
            } completion:^(BOOL finished) {
                dataFlag = YES;
                NSLog(@"向上移动·");
            }];
        }
        
    }
    if (indexPath.section == 0 && [indexPath row] == 3)
    {
        //修改电子邮件
        if ((NSNull *)stringEmail == [NSNull null]) {
            stringEmail = @"";
        }else
            
            stringEmail = del.currentUser.userMail;
        
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"电子邮件" message:stringEmail delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        alert.tag = 1000+1;
        alert.alertViewStyle = UIAlertViewStylePlainTextInput;
        textMail = [alert textFieldAtIndex:0];
        if ((NSNull *)del.currentUser.userMail == [NSNull null]) {
            stringEmail = @"";
        }else
            
            textMail.text = [contact getChangeValue];
        [alert show];
        
    }
    if (indexPath.section == 1 && [indexPath row] == 0) {
        //修改密码
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"请输入旧密码" message:nil  delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        alert.tag = 1000+2;
        alert.alertViewStyle = UIAlertViewStyleSecureTextInput;
        textPwd = [alert textFieldAtIndex:0];
        //        textPwd.text = [contact getChangeValue];
        [alert show];
    }
    
}

#pragma mark 返回分组的名字
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    
    HYLContactGroup *group = dataArray[section];
    return group.name;
}
#pragma mark - alert代理方法
#pragma mark alert的点击方法
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == 1000 + 1)
    {   //tag = 1000 + 1 修改电子邮件
        if (buttonIndex == 1) {
            del.currentUser.userMail = textMail.text ;
            stringEmail = textMail.text;
            [self initData];
            [tableViewDate reloadData];
        }
    }
    if (alertView.tag == 1000 + 2)
    {   //tag = 1000 + 2 修改密码
        if (buttonIndex == 1) {
            
            //验证密码是否正确，如果正确，跳转到输入新密码界面，否则直接返回
            NSString *oldPwd = textPwd.text;
            if ([oldPwd isEqualToString:@""]) {//判断是否为空
                return;
            }
            
            __block int result;
            HUD = [[MBProgressHUD alloc] initWithView:self.view];
            [self.view addSubview:HUD];
            [HUD showAnimated:YES whileExecutingBlock:^{
                //判断密码是否正确
                result = [self checkPassword:oldPwd];
            } completionBlock:^{
                
                switch (result) {
                    case -2:
                    case -1:
                    {
                        [HUD removeFromSuperview];
                        HUD = nil;
                        
                        HUD = [[MBProgressHUD alloc] initWithView:self.view];
                        [self.view addSubview:HUD];
                        
                        HUD.mode = MBProgressHUDModeText;
                        HUD.labelText = @"验证密码操作失败!";
                        [HUD showAnimated:YES whileExecutingBlock:^{
                            sleep(1);
                        } completionBlock:^{
                            [HUD removeFromSuperview];
                            HUD = nil;
                        }];
                    }
                        break;
                    case 0:
                    {
                        [HUD removeFromSuperview];
                        HUD = nil;
                        
                        HUD = [[MBProgressHUD alloc] initWithView:self.view];
                        [self.view addSubview:HUD];
                        
                        HUD.mode = MBProgressHUDModeText;
                        HUD.labelText = @"密码错误!";
                        [HUD showAnimated:YES whileExecutingBlock:^{
                            sleep(1);
                        } completionBlock:^{
                            [HUD removeFromSuperview];
                            HUD = nil;
                        }];
                    }
                        break;
                    case 1:
                    {
                        
                        //跳转
                        VOLChangePasswordViewController *changePwdVC = [self.storyboard instantiateViewControllerWithIdentifier:@"changePwdController"];
                        [HUD removeFromSuperview];
                        HUD = nil;
                        [self.navigationController pushViewController:changePwdVC animated:YES];
                    }
                        break;
                        
                        
                }
                
            }];
            
        }
        
    }
    if (alertView.tag == 1000 + 3)
    {   //tag = 1000 + 3 修改名字
        if (buttonIndex == 1) {
            stringName = textName.text;
            del.currentUser.userName = textName.text ;
            [self initData];
            [tableViewDate reloadData];
        }
        
    }
}

#pragma mark - UIPickerView代理方法
#pragma mark sexPicker的代理
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    
    return 1;
}
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    
    return [arraySex count];
}

-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    
    return [arraySex objectAtIndex:row];
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    stringSex = [arraySex objectAtIndex:row];
    
}
#pragma mark 保存修改的资料
-(void)savePersonData :(id) sender
{
    __block int isSubmit;
    HUD = [[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:HUD];
    HUD.labelText = @"正在保存...";
    [HUD showAnimated:YES whileExecutingBlock:^{
        //调用方法保存数据
        isSubmit = [self submitData];
    } completionBlock:^{
        [HUD removeFromSuperview];
        HUD = nil;
        
        HUD = [[MBProgressHUD alloc] initWithView:self.view];
        [self.view addSubview:HUD];
        HUD.mode = MBProgressHUDModeText;
        switch (isSubmit) {
            case -1:
                HUD.labelText = @"请求失败";
                break;
            case 0:
                //                HUD.labelText = @"保存失败-_-#";
                [HUD removeFromSuperview];
                HUD = nil;
                //返回
                back;
                break;
            case 1:
                HUD.labelText = @"修改成功^_^";
                break;
        }
        //显示
        [HUD showAnimated:YES whileExecutingBlock:^{
            sleep(1);
        } completionBlock:^{
            [HUD removeFromSuperview];
            HUD = nil;
            //如果修改成功，修改del.currentUser的信息返回
            if (isSubmit == 1) {
                del.currentUser.userName = stringName;
                del.currentUser.userSex = stringSex;
                del.currentUser.userBirth = birth;
                del.currentUser.userMail = stringEmail;
                del.currentUser.userPassword = stringPwd;
                back;
            }
        }];
    }];
}
#pragma mark 上传数据
-(int)submitData{
    NSString *urlString = [NSString stringWithFormat:@"%@user/changeInfo",kHTTPHome];
    NSURL *url = [NSURL URLWithString:urlString];
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
    //设置发送的数据
    [request setPostValue:stringName forKey:@"userName"];
    //    [request setPostValue:stringPwd forKey:@"userPWD"];
    [request setPostValue:stringEmail forKey:@"userMail"];
    [request setPostValue:stringSex forKey:@"usersex"];
    [request setPostValue:[NSString stringWithFormat:@"%f",birth] forKey:@"userbirth"];
    [request setPostValue:[NSString stringWithFormat:@"%d",del.currentUser.userID] forKey:@"userID"];
    //设置发送方式
    [request setRequestMethod:@"POST"];
    [request startSynchronous];
    
    //获得返回数据
    NSData *data = [request responseData];
    if (data) {
        NSDictionary *dic = [json objectWithData:data];
        int status = [[dic objectForKey:@"status"] intValue];
        return status;
    }else{
        NSLog(@"saveUserInfo-------data为空");
        return -1;
    }
    
    
    
}

@end
